﻿using System;
using System.IO;
using System.Xml.Serialization;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace VRA
{
   public class con_settings
    {
      
       public string path = Application.StartupPath + @"\settings.xml";
       private string _connect_string;

       public con_settings()
       { 
       }
       //Запись настроек в файл
       public void WriteXml()
       {
           XmlSerializer ser = new XmlSerializer(typeof(string)); 
           TextWriter writer = new StreamWriter(this.path);
           ser.Serialize(writer, this._connect_string);
           writer.Close();
       }

       //Чтение настроек из файла
       public string ReadXml()
       {
           if (File.Exists(this.path))
           {
               XmlSerializer ser = new XmlSerializer(typeof(string));
               TextReader reader = new StreamReader(this.path);
               this._connect_string = ser.Deserialize(reader) as string;
               reader.Close();
           }
           else 
           {
               MessageBox.Show("Отсутствует файл натроек, настройки будут сгенерированы по умолчанию!");
               this._connect_string = this.set_default_settings();
               this.WriteXml();
           }
           return this._connect_string;
       }

       private string set_default_settings()
       {
           SqlConnectionStringBuilder Connect = new SqlConnectionStringBuilder();

           Connect.DataSource = @"HOME-3F15D21029";
           Connect.InitialCatalog = "vra_db";
           Connect.UserID = "MrAnderson";
           Connect.Password = "qwerty";
           Connect.IntegratedSecurity = true;
           Connect.PersistSecurityInfo = false;
           Connect.ConnectTimeout = 10;

           return Connect.ConnectionString;
       }

       public void set_user_settings(string server, string db, string user, string pass, bool security)
       {
           SqlConnectionStringBuilder Connect = new SqlConnectionStringBuilder();

           Connect.DataSource = @server;
           Connect.InitialCatalog = @db;
           Connect.UserID = user;
           Connect.Password = pass;
           Connect.PersistSecurityInfo = security;

           this._connect_string = Connect.ConnectionString;
           this.WriteXml();
       }
    }
}
